package com.xiaoyu.izf.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaoyu.izf.model.NewsInfo;
import com.xiaoyu.izf.repository.NewsInfoDao;
import com.xiaoyu.izf.util.HttpsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class DataGetService {
    @Autowired
    private NewsInfoDao newsInfoDao;

    public String userTokenGet(){
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("username", "17711378955");
        params.put("password", "1q2w3e4r");
        JSONObject json = HttpsUtils.doPost("http://zhaolianmall.weirong100.com/Api/User/loginApi", params);
        String token = json.getString("token");
        newsListGet(token);
        return token;
    }

    public void newsListGet(String token){
        HashMap<String, Object> params2 = new HashMap<String, Object>();
        params2.put("token", "d593rbAVIipcPnMZMSY9YXcLBKb1NpNErxw6g8LCNAvPzKDUxw");
        params2.put("page", 1+"");
        JSONObject json1 = HttpsUtils.doPost("http://zhaolianmall.weirong100.com/api/User/getArticleListApi", params2);
        JSONArray jsonArray = json1.getJSONArray("data");
        for (int i = 0; i <jsonArray.size() ; i++) {
            JSONObject json = jsonArray.getJSONObject(i);
            NewsInfo news = new NewsInfo();
            news.setId(json.getIntValue("id"));
            news.setImg(json.getString("img"));
            news.setAddTime(json.getTimestamp("addtime"));
            news.setDescription(json.getString("description"));
            news.setTitle(json.getString("title"));
            news.setClick(json.getIntValue("click"));
            NewsInfo one = newsInfoDao.findOneById(news.getId());
            if(one==null) {
                newsOne(token, news.getId(), news);
            }
        }

    }

    public void newsOne(String token, int id, NewsInfo newsInfo){
        HashMap<String, Object> params3 = new HashMap<String, Object>();
        params3.put("token", token);
        params3.put("article_id", id+"");
        JSONObject json = HttpsUtils.doPost("http://zhaolianmall.weirong100.com/api/User/getArticleDetailApi", params3);
        newsInfo.setEditor(json.getString("editor"));
        newsInfo.setThumb("http://zhaolianmall.weirong100.com"+json.getString("thumb"));
        newsInfo.setHot(json.getIntValue("hot"));
        newsInfo.setDetail(json.getString("content"));
        newsInfo.setCid(json.getIntValue("cid"));
        newsInfo.setIsDel(0);
        newsInfoDao.save(newsInfo);
    }
}
